package com.jstyle.beatecg.fragment;

import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;


import com.jstyle.beatecg.NetWork.NetWorkUtil;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.activity.AboutUsActivity;
import com.jstyle.beatecg.activity.BindDeviceActivity;
import com.jstyle.beatecg.activity.LoginActivity;
import com.jstyle.beatecg.activity.MainActivity;
import com.jstyle.beatecg.activity.OtaActivity;
import com.jstyle.beatecg.activity.UserInfoActivity;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.base.BaseFragment;
import com.jstyle.beatecg.ble.BleManager;
import com.jstyle.beatecg.ble.BleService;
import com.jstyle.beatecg.daoManager.UserInfoDaoManager;
import com.jstyle.beatecg.model.BleData;
import com.jstyle.beatecg.model.MyBluetoothDevice;
import com.jstyle.beatecg.model.UpdateData;
import com.jstyle.beatecg.model.UserInfo;
import com.jstyle.beatecg.util.GlobalConast;
import com.jstyle.beatecg.util.ImageUtils;
import com.jstyle.beatecg.util.NetWorkConast;
import com.jstyle.beatecg.util.NetWorkException;
import com.jstyle.beatecg.util.ResolveData;
import com.jstyle.beatecg.util.RxBus;
import com.jstyle.beatecg.util.ScreenUtils;
import com.jstyle.beatecg.util.SendData;
import com.jstyle.beatecg.util.SharePreferenceUtils;
import com.jstyle.beatecg.view.FileUpdateDialog;
import com.jstyle.beatecg.view.HeadCircleView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import no.nordicsemi.android.dfu.DfuBaseService;
import okhttp3.ResponseBody;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link UserFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserFragment extends BaseFragment {
    private static final String TAG = "UserFragment";
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    @BindView(R.id.iv_user_usericon)
    ImageView ivUserUsericon;
    @BindView(R.id.lianjie_status)
    ImageView lianjie_status;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.bt_user_bindDevice)
    Button btUserBindViewDevice;
    @BindView(R.id.bt_user_battery)
    Button btUserBattery;
    @BindView(R.id.bt_user_auto)
    Button btUserAuto;

    @BindView(R.id.bt_user_aboutus)
    Button btUserAboutus;
    @BindView(R.id.bt_uset_sign_out)
    Button btUsetSignOut;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.bt_user_language)
    Button btUserLanguage;

    @BindView(R.id.tv_uset_editname)
    TextView tvUsetEditname;
    @BindView(R.id.tv_user_new_version)
    TextView tvUserNewVersion;
    @BindView(R.id.rb_language_cn)
    RadioButton rbLanguageCn;
    @BindView(R.id.rb_language_eh)
    RadioButton rbLanguageEh;
    @BindView(R.id.rg_user_change_language)
    RadioGroup rgUserChangeLanguage;
    @BindView(R.id.iv_battery_level)
    ImageView ivBatteryLevel;
    @BindView(R.id.lanya_status)
    Button lanya_status;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private Bitmap bm;
    private HeadCircleView circleView;
    private Disposable subscription;
    private String deviceAddress;
    Dialog batteryDialog;
    private String deviceVersion;
    private String downLoadFilePath;
    private String versions;
    public UserFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static UserFragment newInstance(String param1, String param2) {
        UserFragment fragment = new UserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        ButterKnife.bind(this, view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ScreenUtils.setStatusBarColor(llTitle, android.R.color.transparent);
        }
        initView(view);
        return view;
    }

    boolean isChangeLa;

    private void initView(View view) {

        subscription = RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData data) throws Exception {
                String action = data.getAction();
                if (BleService.ACTION_DATA_AVAILABLE.equals(action)) {
                 final    byte[] value = data.getValue();
                    if (value[0] == SendData.CMD_GET_BATTERY) {
                       new Handler().post(new Runnable() {
                           @Override
                           public void run() {
                               if(null==versions)return;
                               if(Integer.valueOf(versions)>4){

                                   if(value[1]*10>100){
                                       int countvalue=Math.round(value[1]/10f);
                                       setImageViewLevel(countvalue);//四舍五入
                                       btUserBattery.setText(value[1]+"%");
                                   }else{
                                       int countvalue=Math.round(value[1]);
                                       setImageViewLevel(countvalue);//四舍五入
                                       btUserBattery.setText(value[1]*10+"%");
                                   }

                               }else{
                                   setImageViewLevel(ResolveData.getValue(value[1], 0));
                                   NumberFormat format = NumberFormat.getPercentInstance();
                                   btUserBattery.setText(format.format(ResolveData.getValue(value[1], 0) / 10f));
                               }

                           }
                       });
                    } else if (value[0] == SendData.CMD_GET_VERSION) {
                        String version = ResolveData.getVersion(value[3]).trim();
                        // String version = "055";
                        versions=version;
                        queryVersion(version);
                    }

                } else if (BleService.ACTION_GATT_CONNECTED.equals(action)) {
                    lianjie_status.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.lianjie));
                }  else if (BleService.ACTION_GATT_DISCONNECTED.equals(action)) {
                    lianjie_status.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.unlianjie));
                }else if(OtaActivity.Action_Dfu_Complete.equals(action)){

                    showHasNewVersion(false);
                }
            }


        });

        String sta = SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_Language);
        rgUserChangeLanguage.check("en".equals(sta) ? R.id.rb_language_eh : R.id.rb_language_cn);
        rgUserChangeLanguage.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_language_eh:
                        SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_Language, "en");
                        break;
                    case R.id.rb_language_cn:
                        SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_Language, "zh");
                        break;
                }
                BleData bleData = new BleData();
                bleData.setAction(ACTION_CHANGELanguage);
                RxBus.getInstance().post(bleData);
                getActivity().finish();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                //   changeAppLanguage();


            }
        });
//        BleManager.getInstance().writeValue(SendData.getBattery());
    }

    public final static String ACTION_CHANGELanguage = "ACTION_CHANGELanguage";
    boolean isNeedUpdate;
    private void queryVersion(final String version) {
        Log.i(TAG, "queryVersion: " + version);
        Map<String, String> queryVersion = new HashMap<>();
        queryVersion.put(NetWorkConast.KEY_DEVICE_VERSION, version);
        //queryVersion.put(NetWorkConast.KEY_DEVICE_VERSION, "013");
        queryVersion.put(NetWorkConast.KEY_type, GlobalConast.VALUE_TYPE);
        NetWorkUtil.getInstance().getJstyleApi().queryDeviceVersion(queryVersion).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<UpdateData>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(UpdateData value) {
                disMissProgressDialog();
                int code = value.getMsgCode();
                Log.i(TAG, "onNext: " + value.toString());
                boolean hasNewVersion=false;
                if (code == GlobalConast.VALUE_NEED_UPDATE) {
                     downLoadFilePath = value.getData().getUrl();
                    deviceVersion = value.getData().getVersion();
                    hasNewVersion=true;
                }
                showHasNewVersion(hasNewVersion);
            }

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void showUpdateDialog(final String filePath) {
        FileUpdateDialog fileUpdateDialog = new FileUpdateDialog(getActivity(), R.style.jstyleDialog_style, deviceVersion);

        fileUpdateDialog.setFileUpdateListener(new FileUpdateDialog.FileUpdateListener() {
            @Override
            public void startUpdateFile() {
                downLoadUpdatePath(filePath);
            }

            @Override
            public void laterUpdateFile() {

            }
        });
        fileUpdateDialog.show();
//        AlertDialog updateDialog = new AlertDialog.Builder(getActivity()).setTitle(" ").setMessage(getString(R.string.Find_New_firmware_version)).setNegativeButton(getString(R.string.cancel), null).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                downLoadUpdatePath(filePath);
//            }
//        }).create();
//        updateDialog.show();
    }

    private void downLoadUpdatePath(final String filePath) {
        String[] filePaths = filePath.split("/");
        final String lastPath = filePaths[filePaths.length - 1];
        showProgressDialog(getString(R.string.Downloading_the_new_firmware));
        NetWorkUtil.getInstance().getJstyleApi().downloadPath(filePath).
                subscribeOn(Schedulers.io()).doOnNext(new Consumer<ResponseBody>() {
            @Override
            public void accept(ResponseBody responseBody) throws Exception {
                writeToDisk(lastPath,responseBody);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBody value) {

            }

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
            }

            @Override
            public void onComplete() {
                Log.i(TAG, "onComplete: ");
                disMissProgressDialog();
                startDfu(lastPath);
            }
        });
    }

    private void startDfu(String lastPath) {
        if (BleManager.getInstance().isConnected()) {
           BleManager.getInstance().writeValue(SendData.entryDfuMode());
            Intent intent = new Intent(getActivity(), OtaActivity.class);
            intent.putExtra(OtaActivity.EXTRA_FILE_PATH, ImageUtils.UPDATEPATH + lastPath);
            startActivity(intent);

        }
    }

    private void writeToDisk(final String filePath, ResponseBody responseBody) throws IOException {
        File file = new File(ImageUtils.UPDATEPATH);
        File fileMusic = new File(ImageUtils.UPDATEPATH + filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
       
        if (fileMusic.exists() && fileMusic.length() == responseBody.contentLength()) return;
        byte[] buffer = new byte[1024 * 8];
        int len;
        FileOutputStream out = new FileOutputStream(fileMusic);
        InputStream in = responseBody.byteStream();
        while ((len = in.read(buffer)) != -1) {
            Log.i(TAG, "writeToDisk: ");
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();


    }

    private void showUserInfo() {
        setHeadIcon();
        MyBluetoothDevice myBluetoothDevice=SharePreferenceUtils.getUser(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS);
        if(null!=myBluetoothDevice){
            if(null!=myBluetoothDevice.getNames()){
            deviceAddress = myBluetoothDevice.getNames();
        } }
        btUserBindViewDevice.setText(!TextUtils.isEmpty(deviceAddress) ? deviceAddress : getString(R.string.Device));
        UserInfo userInfo = UserInfoDaoManager.getUser(SharePreferenceUtils.account_default);
        String name = GlobalConast.DEFAULT_NAME;
        if (userInfo != null) name = userInfo.getName();
        tvUsetEditname.setText(TextUtils.isEmpty(name) ? GlobalConast.DEFAULT_NAME : name);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            BleManager.getInstance().writeValue(SendData.getDeviceVersion());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    BleManager.getInstance().writeValue(SendData.getBattery());//电量
                }
            }, 500);

        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        showUserInfo();
     if(BleManager.getInstance().isConnected()){
         lianjie_status.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.lianjie));
         lanya_status.setText(getResources().getString(R.string.connected));
     }else{
         lianjie_status.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.unlianjie));
         lanya_status.setText(getResources().getString(R.string.unconnected));
     }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (isChangeLa) {

        }
        unsubscribe();

    }



    @OnClick({R.id.iv_user_usericon, R.id.tv_uset_editname, R.id.bt_user_bindDevice, R.id.bt_user_battery, R.id.bt_user_auto, R.id.bt_user_aboutus, R.id.bt_uset_sign_out
    ,R.id.bt_user_bindDeviceRt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_user_usericon:
                startActivity(UserInfoActivity.class);
                break;
            case R.id.tv_uset_editname:
                startActivity(UserInfoActivity.class);
                break;
            case R.id.bt_user_bindDeviceRt:
            case R.id.bt_user_bindDevice:
                startActivity(BindDeviceActivity.class);
                break;
            case R.id.bt_user_battery:
                //checkBattery();
                break;
            case R.id.bt_user_auto:
                if(isNeedUpdate){
                    showUpdateDialog(downLoadFilePath);
                }else{
                    showToast(getString(R.string.Latest_Version_Already));
                }

                break;

            case R.id.bt_user_aboutus:
                startActivity(AboutUsActivity.class);
                break;
            case R.id.bt_uset_sign_out:
                startActivity(LoginActivity.class);
                SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_AUTH_USERID, "");
                SharePreferenceUtils.setSpBoolean(SharePreferenceUtils.KEY_LOGIN, false);
                getActivity().finish();
                break;

        }
    }

    private void checkVersion() {
        if (BleManager.getInstance().isConnected()) {
            showProgressDialog(getString(R.string.check_firmware_version));
            BleManager.getInstance().writeValue(SendData.getDeviceVersion());
        } else {
            showToast(getString(R.string.Bluetooth_Disconnected));
        }

    }

    private void setHeadIcon() {
        bm = ImageUtils.findHeadBitmap(getActivity()) == null ? BitmapFactory.decodeResource(getResources(),
                R.drawable.user_icon) : ImageUtils.findHeadBitmap(getActivity());
        circleView = new HeadCircleView(bm);
        ivUserUsericon.setImageDrawable(circleView);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void setImageViewLevel(int level) {

        ivBatteryLevel.setImageLevel(level);
    }

//    private void checkBattery(byte[] value) {//1电池等级，4 5电压
//        int voltage = Integer.valueOf(String.format("%02X", value[4])) * 100 + Integer.valueOf(String.format("%02X", value[5]));
//        Log.i(TAG, "checkBattery: " + voltage);
//        if (voltage > 364) return;
//        if (batteryDialog == null) {
//            batteryDialog = new Dialog(getActivity());
//            batteryDialog.setContentView(R.layout.dialog_alert_battery);
//            batteryDialog.findViewById(R.id.iv_dialog_off).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    batteryDialog.dismiss();
//                }
//            });
//            ViewGroup.LayoutParams lay = batteryDialog.getWindow().getAttributes();
//            lay.width = ScreenUtils.getScreenWidth(getActivity());
//        }
//        batteryDialog.show();
//    }

    private void showHasNewVersion(boolean hasNewVersion) {
        isNeedUpdate=hasNewVersion;
        tvUserNewVersion.setVisibility(hasNewVersion ? View.VISIBLE : View.INVISIBLE);
    }

    private void unsubscribe() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }
}
